<template>
	<view>
		<view class="header">
			<view class="bg">
				<view class="box">
					<view class="box-hd">
						<view class="avatar">
							<image :src="userInfo.Avatar" />
						</view>
						<view class="phone-number">{{ userInfo.NickName }}</view>
					</view>
					<view class="box-bd">
						<navigator class="item" url="/pages/sys/profile/changePassword" open-type="navigate">
							<view class="icon"><image :src="lockImg" /></view>
							<view class="text">{{ $t('pages.sys.profile.modifyPasswordText') }}</view>
						</navigator>
						<navigator class="item" url="/pages/sys/profile/profileEdit" open-type="navigate">
							<view class="icon"><image :src="userEditImg" /></view>
							<view class="text">{{ $t('pages.sys.profile.modifyProfileText') }}</view>
						</navigator>
						<view class="item" @tap="handleLogout()">
							<view class="icon"><image :src="exitImg" /></view>
							<view class="text">{{ $t('pages.sys.profile.logoutText') }}</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="list-content">
			<view class="list">
				<view class="li noborder" @tap="showOrganizationTree">
					<view class="icon"><image src="@/static/images/app/organization@128x.png"></image></view>
					<view class="text">{{ `${$t('pages.sys.profile.currentOrgText')} ： ${currentOrgInfo.Name}` }}</view>
					<image class="to" src="@/static/images/app/arrow_right@200x.png"></image>
				</view>
			</view>
			<view class="list">
				<picker @change="confirmLangHandler" mode='selector' range-key="text" :value="localeLangIndex" :range="localeLangs">
					<view class="li">
						<view class="icon"><image src="@/static/images/app/language_letter@128x.png"></image></view>
						<view class="text">{{ `${$t('common.languageText')} ： ${localeLangs[localeLangIndex].text}` }}</view>
						<image class="to" src="@/static/images/app/arrow_right@200x.png"></image>
					</view>
				</picker>
				<navigator url="/pages/sys/profile/confirmPhone" open-type="navigate">
					<view class="li">
						<view class="icon"><image src="@/static/images/app/phone_apple_ipad@128x.png"></image></view>
						<view class="text">{{ `${$t('pages.sys.profile.mobileText')} ： ${userInfo.PhoneNumber}` }}</view>
						<image class="to" src="@/static/images/app/arrow_right@200x.png"></image>
					</view>
				</navigator>
				<navigator url="/pages/sys/profile/printerSetup" open-type="navigate">
					<view class="li">
						<view class="icon"><image src="@/static/images/app/printer@128x.png"></image></view>
						<view class="text">{{ `${$t('pages.sys.profile.printerSetupText')}` }}</view>
						<image class="to" src="@/static/images/app/arrow_right@200x.png"></image>
					</view>
				</navigator>
				<navigator url="/pages/sys/profile/connectionSetup" open-type="navigate">
					<view class="li">
						<view class="icon"><image src="@/static/images/app/web_connection@128x.png"></image></view>
						<view class="text">{{ `${$t('pages.sys.profile.connectionSetupText')}` }}</view>
						<image class="to" src="@/static/images/app/arrow_right@200x.png"></image>
					</view>
				</navigator>
				<navigator url="/pages/sys/profile/scanSetup" open-type="navigate">
					<view class="li">
						<view class="icon"><image src="@/static/images/app/scan_barcode@128x.png"></image></view>
						<view class="text">{{ `${$t('pages.sys.profile.scanSetupText')}` }}</view>
						<image class="to" src="@/static/images/app/arrow_right@200x.png"></image>
					</view>
				</navigator>
				<navigator url="/pages/sys/about/index" open-type="navigate">
					<view class="li">
						<view class="icon"><image src="@/static/images/app/info_orange@128x.png"></image></view>
						<view class="text">{{ `${$t('pages.sys.profile.aboutUsText')}` }}</view>
						<image class="to" src="@/static/images/app/arrow_right@200x.png"></image>
					</view>
				</navigator>
			</view>
			<view class="list">
				<view class="li noborder" @click="changeTheme">
					<view class="icon"><image src="@/static/images/app/design_cup_graphics@128x.png"></image></view>
					<view class="text">{{ $t('pages.sys.profile.changeThemeText') }}</view>
					<image class="to" src="@/static/images/app/arrow_right@200x.png"></image>
				</view>
			</view>
			<view class="list">
				<view class="li noborder" @click="checkUpgrade">
					<view class="icon"><image src="@/static/images/app/upgrade@128x.png"></image></view>
					<view class="text">{{ $t('pages.sys.profile.upgradeCheckText') }}</view>
					<image class="to" src="@/static/images/app/arrow_right@200x.png"></image>
				</view>
			</view>
		</view>

		<tki-tree ref="tkitree" :selectParent="false" :multiple="false" :foldAll="false" :range="orgTreeNodes" idKey="Id" rangeKey="Name"
				confirmColor="#007AFF" :title="$t('pages.sys.profile.currentOrgChangeText')" titleColor="#007AFF" :border="true"
				@confirm="organizationTreeConfirm" @cancel="organizationTreeCancel"></tki-tree>
		<upgrade-center ref="upgradeCenter" theme="blue" url="/api/mobile/checkUpgrade" :autoCheck="false"></upgrade-center>

		<view style="margin-top: 80rpx;" />
	</view>
</template>
<script>
	import { getLocalelang, setLocalelang, getLocalelangDesc } from "@/locales/setupI18n";
	import { localeLangs } from '@/locales/index.d';
	import lockImg from '@/static/images/app/lock_password@128x.png';
	import userEditImg from '@/static/images/app/user_male_edit@128x.png';
	import exitImg from '@/static/images/app/exit_logout@128x.png';
	import tkiTree from '@/components/tki-tree/tki-tree.vue';
	import UpgradeCenter from '@/components/upgrade-center-app/upgrade.vue';
  import { handleScan } from '@/logics/scanHandler';
	import { getOrganizationNode, getOrganizationTree } from '@/apis/identity';
	import { useScan } from "@/utils/scan-code";
	const { scan } = useScan();
	export default {
		components: {
			tkiTree,
			UpgradeCenter
		},
		data() {
			return {
				orgTreeNodes: [],
				userInfo: {
					UserId: null,
					UserName: null,
					NickName: null,
					Email: null,
					PhoneNumber: null,
					Avatar: null,

					Gender: null,
					Birthday: null,
					BloodType: null,
					Tag: null,
					Title: null,
					Address: null,
					Profile: null,
					Signature: null,

					ChineseBirthday: null,
					Age: null,
					ZodiacSign: null,
					StarSign: null,

					Remark: null,
					IsAdmin: null,

					IsRefreshNext: null,

					Roles: null,

					CurrentOrganization: null,
					CurrentDepartment: null,

					ExtendData: null,
				},
				currentOrgInfo: {},
				localeLangs,
				localeLangIndex: 0,
				localeLang: '',
				localeLangDesc: '',
				lockImg,
				userEditImg,
				exitImg,
			};
		},
		onLoad() {},
		onShow() {
			const that = this;
			// 导航栏多语言
			uni.setNavigationBarTitle({
				title: that.$t('pages.sys.profile.profileTitleText'),
			});
			// console.log('getUserInfo', that.$store.getters.getUserInfo);
			that.userInfo = that.$store.getters.getUserInfo;
			// console.log('getUserInfo', that.userInfo);
			// 当前组织机构信息
			const organizationId = that.userInfo.CurrentDepartment ? that.userInfo.CurrentDepartment.Id : that.userInfo.CurrentOrganization ? that.userInfo.CurrentOrganization.Id : 0;
			let organizationName = '';
			if(that.userInfo.CurrentOrganization){
				organizationName = that.userInfo.CurrentOrganization.Name ? that.userInfo.CurrentOrganization.Name : that.userInfo.CurrentOrganization.Id;
			}
			if(that.userInfo.CurrentDepartment){
				organizationName = `${organizationName} - ${that.userInfo.CurrentDepartment.Name ? that.userInfo.CurrentDepartment.Name : that.userInfo.CurrentDepartment.Id}`;
			}
			that.currentOrgInfo = { Id: organizationId, Name: organizationName };
			// 本地化语言
			that.localeLang = getLocalelang();
			that.localeLangDesc = getLocalelangDesc(that.localeLang);
			for (let i = 0; i < localeLangs.length; i++){
				if(localeLangs[i].value === that.localeLang){
					that.localeLangIndex = i;
					break;
				}
			}
			// 监听扫描
			scan.start(async(res) => {
				// console.log('扫描结果', res);
				await handleScan(res);
			});
		},
		destroyed: function(){
			// uni.showModal({
			//     title: 'destroyed',
			//     content: '停止监听扫描'
			// });
			// 页面退出时一定要停止监听扫描,否则监听将一直有效
			scan.stop();
		},
		methods: {
			/** 显示组织机构树形选择器 */
			async showOrganizationTree() {
				const that = this;
				const result = await getOrganizationTree();
				if (result.Type === 200) {
					let data = result.Data;
					if (data?.length > 0) {
						that.orgTreeNodes = JSON.parse(JSON.stringify(data).replace(/Items/g, 'children'));
						that.setOrgTreeNodes(that.orgTreeNodes);

						that.$refs.tkitree._show();
					}
				}
			},
			/** 设置组织机构树形数据 */
			setOrgTreeNodes(datas){ //遍历树  获取id数组
			const that = this;
			  for(var i in datas){
			    // this.expandedKeys.push(datas[i].id)  // 遍历项目满足条件后的操作
				if(datas[i].Id === that.currentOrgInfo.Id){
					datas[i].checked = true;
				}
			    if(datas[i].children){  //存在子节点就递归
			      that.setOrgTreeNodes(datas[i].children);
			    }
			  }
			},
			/** 组织机构树形选择器确定回调事件 */
			async organizationTreeConfirm(e) {
				// console.log('organizationTreeConfirm', e);
				const that = this;
				if(e !== undefined && e !== null && e.length > 0){
					const selectedId = e[0].Id;
					// console.log('organizationTreeConfirm', { that.currentOrgInfo.Id, selectedId });
					if (that.currentOrgInfo.Id === selectedId) {
						uni.showToast({
							title: that.$t('pages.sys.profile.currentOrgNotChanged'),
							icon: 'none',
							duration: 2000
						});
					  return;
					}

					try {
						uni.showLoading({
							title: that.$t('common.loadingText'),
							mask: true
						});

						const userInfo = await that.$store.dispatch('setOrganization', { organizationId: selectedId, mode: 'modal' });
						uni.hideLoading();
						if (userInfo !== undefined && userInfo !== null) {
							// that.userInfo = that.$store.getters.getUserInfo;
							that.userInfo = userInfo;
							// console.log('getUserInfo', that.userInfo);
							// 当前组织机构信息
							const organizationId = that.userInfo.CurrentDepartment ? that.userInfo.CurrentDepartment.Id : that.userInfo.CurrentOrganization ? that.userInfo.CurrentOrganization.Id : 0;
							let organizationName = '';
							if(that.userInfo.CurrentOrganization){
								organizationName = that.userInfo.CurrentOrganization.OrgName ? that.userInfo.CurrentOrganization.OrgName : that.userInfo.CurrentOrganization.Id;
							}
							if(that.userInfo.CurrentDepartment){
								organizationName = `${organizationName} - ${that.userInfo.CurrentDepartment.OrgName ? that.userInfo.CurrentDepartment.OrgName : that.userInfo.CurrentDepartment.Id}`;
							}
							that.currentOrgInfo = { Id: organizationId, Name: organizationName };

							uni.showToast({
								title: that.$t('common.successText'),
								icon: 'success',
								duration: 2000
							});
						}
					}
					catch(err) {}
					finally {
						uni.hideLoading();
					}
				}
			},
			/** 组织机构树形选择器取消回调事件 */
			organizationTreeCancel(e) {
				// console.log('organizationTreeCancel', e);
			},
			/** 确认语言选择 */
			confirmLangHandler(e) {
				const that = this;
				// console.log('confirm', e);

				// <picker> 控件用
				if(e && e.detail){
					const selectedIndex = e.detail.value;
					if(selectedIndex >= 0){
						that.localeLangIndex = selectedIndex;
						that.localeLang = that.localeLangs[that.localeLangIndex].value;
						that.localeLangDesc = that.localeLangs[that.localeLangIndex].text;
						// console.log('confirm', that.localeLang);
						setLocalelang(that.localeLang);
						that.$i18n.locale = that.localeLang;
					}
				}
			},
			/** 处理登出 */
			async handleLogout() {
				const that = this;
				uni.showModal({
					title: that.$t('common.warmReminderText'),
					content: that.$t('common.exitConfirmText'),
					success: function(res) {
						if (res.confirm) {
							uni.showLoading({
							    title: that.$t('common.loadingText')
							});

							that.$store.dispatch('logout', true).then(()=>{
								uni.hideLoading();
								// plus.runtime.quit(); // 退出APP
								// // 保留当前页面，跳转到登录页
								// uni.navigateTo({
								// 	url: '/pages/sys/login/login',
								// 	passedParams: {
								// 		info: '已登出',
								// 	},
								// });
								// // // 关闭所有页面，打开到登录页（这种方式貌似会让该页面扫描监听失效，暂注释）
								// // uni.reLaunch({
								// // 	url: '/pages/sys/login/login',
								// // 	passedParams: {
								// // 		info: '已登出',
								// // 	},
								// // });
							});

							uni.hideLoading();
						}
					},
				});
			},
			/** 更换主题 */
			changeTheme(){
				uni.navigateTo({
						url: '../../theme-change/index'
				});
			},
			/** 检查更新 */
			async checkUpgrade(){
				const that = this;
				const resultDto = await that.$refs.upgradeCenter.checkUpgrade();
				if(resultDto.Upgrade === false){
					uni.showToast({
						title: that.$t('component.upgradeCenterApp.latestVersionText'),
						icon:'none',
					});
				}
			},
		}
	}
</script>

<style lang="scss">
page{
	background-color: #f1f1f1;
	font-size: 30upx;
}
.header{
	background: #fff;
	height: 290upx;
	padding-bottom: 110upx;
	.bg{
		width: 100%;
		height: 200upx;
		padding-top: 100upx;
		background-color: #007AFF;
	}
}
.box{
	width: 650upx;
	height: 280upx;
	border-radius: 20upx;
	margin: 0 auto;
	background: #fff;
	box-shadow: 0 5upx 20upx 0upx rgba(0, 0, 150, .2);
	.box-hd{
		display: flex;
		flex-wrap: wrap;
		flex-direction: row;
		justify-content: center;
		.avatar{
			width: 160upx;
			height: 160upx;
			background: #fff;
			border: 5upx solid #fff;
			border-radius: 50%;
			margin-top: -80upx;
			overflow: hidden;
			image{
				width: 100%;
				height: 100%;
			}
		}
		.phone-number{
			width: 100%;
			text-align: center;
		}
	}
	.box-bd{
		display: flex;
		flex-wrap: nowrap;
		flex-direction: row;
		justify-content: center;
		.item{
			flex: 1 1 auto;
			display: flex;
			flex-wrap: wrap;
			flex-direction: row;
			justify-content: center;
			border-right: 1px solid #f1f1f1;
			margin: 15upx 0;
			padding: 5px;
			&:last-child{
				border: none;
			}
			.icon{
				width: 60upx;
				height: 60upx;
				image{
					width: 100%;
					height: 100%;
				}
			}
			.text{
				width: 100%;
				text-align: center;
				margin-top: 10upx;
			}
		}
		.item:active {
		    background-color: #f8f8f8;
		}
	}
}
.list-content{
	background: #fff;
}
.list{
	width: 100%;
	border-bottom: 15upx solid  #f1f1f1;
	background: #fff;
	&:last-child{
		border: none;
	}
	.li{
		width: 92%;
		height: 100upx;
		padding: 0 4%;
		border-bottom: 1px solid rgb(243,243,243);
		display: flex;
		align-items: center;
	&.noborder{
		border-bottom: 0
		}
		.icon{
			flex-shrink: 0;
			width: 50upx;
			height: 50upx;
			image{
				width: 50upx;
				height: 50upx;
			}
		}
		.text{
			padding-left: 20upx;
			width: 100%;
			color: #666;
		}
		.to{
			flex-shrink: 0;
			width: 40upx;
			height: 40upx;
		}
	}
	.li:active {
	    background-color: #f8f8f8;
	}
}
</style>
